﻿ 
function JsonStringToDate(str) {
    try{
        var re = /-?\d+/;
        var m = re.exec(str); 
        return new Date(parseInt(m[0]));
    }catch(e){
        return new Date(1970,1,1);
    }
}

Date.prototype.format = function (format) //author: meizz
{
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(),    //day
        "h+": this.getHours(),   //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
    (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
      RegExp.$1.length == 1 ? o[k] :
        ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}

// 按【2012-02-13 09:09:09】的格式返回日期
function formatTime(val) {
    try {
        if (val.indexOf('-') >= 0) {
            return val;
        }
        else {
            var d = new Date();
            var re = /-?\d+/;
            var m = re.exec(val);
            var d = new Date(parseInt(m[0]));
            return d.format("yyyy-MM-dd hh:mm:ss");
        }
    } catch (e) {
        return "";
    }
}
function formatDate(val) {
    try {
        if (val.indexOf('-') >= 0) {
            return val;
        }
        else {
            var d = new Date();
            var re = /-?\d+/;
            var m = re.exec(val);
            var d = new Date(parseInt(m[0]));
            return d.format("yyyy-MM-dd");
        }
    } catch (e) {
        return "";
    }
}

//获取URL对应
function getQueryStringByName(name) {
    var result = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
    if (result == null || result.length < 1) {
        return "";
    }
    return result[0].replace(name + '=', '').replace('?', '').replace('&', '');
}

function formatter_IsNo(value, rec) { 
    return (value == null || value.trim() == '0') ? '<span style="color:Red">否</span>' : '<span style="color:#216499">是</span>';
}

 

function formatter_RMB(value, rec) {
    return '<span style="color:#216499">' + value/100 + '元</span>';
}
 
//保留对应位数
function MarkPrecision(value, Precision) {
    return parseInt(value * Precision) / Precision;
}

//利用匿名函数将脚本包裹起来
(function(){
//自定义命名空间v
var onluy={
		model:{},
		ui:{},
		formatter:{},
		loader:{}  ,
		ajax:{}
};

onluy.ui.ShowException= function(data) {
    $('#PopWindowContet').html("异常信息："+data);
    $('#PopWindow').window({
        width: 400,
        height: 100,
        collapsible:false,
        minimizable:false,
        maximizable:false,
        title:'异常',
        modal: true
    });
    $('#PopWindow').window('open');
}




onluy.basePath =function(){
	return  $('#basePath').val();
}
 

//封包加解密 
onluy.encryptByDES=function(message,key) {   
	var keyHex = CryptoJS.enc.Utf8.parse(key);  
	var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7
	}); 
	return encrypted.toString();
} 
 
onluy.decryptByDES=function(ciphertext,key) { 
	var keyHex = CryptoJS.enc.Utf8.parse(key); 
	var decrypted = CryptoJS.DES.decrypt({
		ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
	}, keyHex, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7
	}); 
	return decrypted.toString(CryptoJS.enc.Utf8);
}

//构造加密数据的封包
onluy.makeParam=function(param,key)
{ 
	var message=''; 
	if (typeof (param) != undefined && typeof (param) == 'object') { 
		message=JSON.stringify(param);
    }
	else{
		message= param; 
	} 
  var enResult = onluy.encryptByDES(message,key);//加密   
  var obj={
    "reqParam":enResult
  }
  return obj;
}


onluy.ajax.getData=function(strUrl,param,key,success,error ) {  
    $.ajax({
        async: false,
        type: "get",
        url: strUrl,
        data: onluy.makeParam(param,key),
        dataType: 'json',
        error: function (rq, textStatus, errorThrown) {
        	//var errmsg={success=false,msg=rq.responseText};
        	alert('aaa'+rq.status);
        	//error(errmsg); 
            //$.messager.alert("错误", rq.statusText + '(' + rq.status + '):' + rq.responseText, "error");
        },
        success: function (result) {
        	var resobj={};
        	if(result.respInfo){
        		resobj=onluy.decryptByDES(result.respInfo,key); 
        		resobj=JSON.parse(resobj);
        	}
        	else{
        		resobj=result;
        	}
        	success(resobj);
        }
    }); 
}

onluy.model = {
	fit: true,
	border: false,
	singleSelect: true,
	fitColumns: true,
	selrow: null,
	getmethod: 'get',
	action: 'add',
    url:{
    	add: "add",
	    update: "update",
	    del: "del",
	    list: "list"
    }, 
    editor:{
        title: "弹出框名称",
    	winid:'',
    	formid:'EditForm',
    	width:720,
    	height:300
    },
    idfield: "编码字段", 
    titlefield: "标题字段",
    toolbar: 'Toolbar',
    datagrid: {
    	id:'Grid', 
    	type:"treegrid" , 
        columns:[],
    },
    searchbox:{
    	namefield:'',
    	valuefield:''},
    secretkey:'e036hlqtculakx38tjw2u9gs',
    model: {}
} 

/*======================loder===============================*/
onluy.model.Loader=function( param,success,error){ 
	var opts = $(this).treegrid('options'); 
    if (!opts.url) {
        return false;
    }  
    onluy.ajax.getData(opts.url,param,onluy.model.secretkey, success,error ); 
    return true;
}
/*================loadfilter=================================*/
onluy.model.loadfilter= function(data){ 
    	var i=0; 
    	for(i=0;i<data.length;i++){ 
    		var temp=data[i];
    		data[i].id=temp[onluy.model.idfield]; 
    		data[i].text=temp[onluy.model.titlefield] ; 
    		if(data[i].childcount && data[i].childcount>0){
        		data[i].state="closed"  ; 
    		}else{
        		data[i].state="open"  ;
    		} 
    	}
        return data;    
}
 

 
onluy.model.FindRowById=function(id) {  
    return $('#'+onluy.model.datagrid.id).treegrid('find', id);
}
onluy.model.ReloadList=function() {
    $('#'+onluy.model.datagrid.id).treegrid('reload');
}

onluy.model.del=function(data) {  
    $.messager.confirm('提示', '确定要删除' + data[onluy.model.titlefield], function (r) {
        if (r) {
        	onluy.ajax.getData(onluy.model.url.del,data,function (result) {
                    var success = result.success;
                    if (success) {
                        $('#'+onluy.model.datagrid.id).treegrid('remove', dat[onluy.model.idfield]);
                        $('#'+onluy.model.datagrid.id).treegrid('clearSelections');
                    }
                    $.messager.alert(success ? "提示" : "错误", result.msg, success ? "" : "error");
                }, function (rq, textStatus, errorThrown) {
                    $.messager.alert("错误", rq.statusText + '(' + rq.status + '):' + rq.responseText, "error");
                }) 
        }
    }); 
} 
onluy.model.Save=function() { 
	var urlstr='';
	
	if(onluy.model.action=='add'){
		urlstr=onluy.model.url.add;
    }
    else{
		urlstr=onluy.model.url.update;
    }
	urlstr +='?catch='+Math.random();
    $('#'+onluy.model.editor.formid).form('submit', {
        url: onluy.basePath()+urlstr,
        onSubmit: function () {
            return $(this).form('validate');
        },
        success: function (data) {  
            try{
                var result=eval('(' + data + ')'); 
                var success = result.success;
                $.messager.alert(success ? "提示" : "错误", result.msg, success ? "" : "error");
                if (success) { 
                    $('#'+onluy.model.editor.winid).dialog('close');
                    onluy.model.ReloadList();
                }
            } catch (e) { 
            	onluy.ui.ShowException(data);
            }
        }
    });
}

onluy.model.ShowEditFormView=function() {  
    //alert(onluy.model.selrow);
    $('#'+onluy.model.editor.formid ).form('clear');
    $('#'+onluy.model.editor.formid).form('load', onluy.model.selrow);
    var title='';
    if(onluy.model.action=='add'){
    	title='新增'+onluy.model.editor.title;
    }
    else{
    	title='编辑'+onluy.model.selrow[onluy.model.idfield];
    }
    $('#'+onluy.model.editor.winid).dialog({
    	title:title,
        //top: "50px",
        resizable: false,
        maximizable: false,
        width:onluy.model.editor.width,
        height: onluy.model.editor.height
    }).dialog('open');  
}
onluy.model.ShowEditForm=function() {  
	onluy.model.ShowEditFormView();
}
onluy.model.BeforeLoad=function (row, param) {  
	var name =$('#'+onluy.model.searchbox.id).searchbox('getName'); 
	var value=$('#'+onluy.model.searchbox.id).searchbox('getValue');  
	if(value!=null && value!=''  && value!=undefined ){ 
		param[name]=value;
	}
} 
onluy.model.DblClickRow= function (  rowData  ) { 
	onluy.model.selrow=rowData;
	onluy.model.ShowEditForm();
}
onluy.model.LoadError=  function (res) {
	onluy.ui.ShowException(res);
}
 
onluy.model.ContextMenu= function (e, node) {
    
}
onluy.model.Init=function(){
	onluy.model.InitTreegrid();
	
}

onluy.model.InitTreegrid=function(){ 
	var url =onluy.basePath()+onluy.model.url.list;  
	$('#'+onluy.model.datagrid.id).treegrid({
	    fit: onluy.model.fit,
	    border: onluy.model.border,
	    singleSelect: onluy.model.singleSelect,
	    fitColumns: onluy.model.fitColumns,
	    method: onluy.model.getmethod,
	    url: url,
	    idField: onluy.model.idfield,
	    treeField: onluy.model.titlefield, 
	    toolbar: '#'+onluy.model.toolbar, 
	    columns:onluy.model.datagrid.columns, 
	    //onLoadError:onluy.model.LoadError,
	    loader:onluy.model.Loader,
	    onBeforeLoad: onluy.model.BeforeLoad,
	    onDblClickRow:onluy.model.DblClickRow, 
	    loadFilter: onluy.model.loadfilter, 
	    onContextMenu: onluy.model.ContextMenu
	}); 
}


////////////////////////////////////////////////////////////
//定义全局变量命令空间
window.Onluy = onluy;
////////////////////////////////////////////////////////////
})();
